package com.s7.recycler.adapter;

import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;

import com.s7.recycler.holder.BaseHolder;
import com.s7.recycler.holder.BaseViewHolder;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administor on 2018\7\10 0010.
 * RecyclerView 适配器--无特殊功能
 * 兼容Grid布局、Linear布局、StaggeredGrid布局
 */
public abstract class BaseRecyclerAdapter<T> extends CompatRecyclerAdapter<T> {

    @NonNull
    @Override
    public BaseHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = getView(parent, getLayoutId());
        return new BaseViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull BaseHolder holder, int position) {

        holder.setRealPosition(position);

        /**
         * 子类实现数据绑定
         */
        if (holder instanceof BaseViewHolder) {
            initClickListener((BaseViewHolder)holder, datas.get(position));
            ((BaseViewHolder) holder).setData(datas.get(position));
            bindData((BaseViewHolder) holder, position, datas.get(position));
        }
    }

    @Override
    public int getItemCount() {
        return datas == null ? 0 : datas.size();
    }

    /**
     * 获取子item
     * @return
     */
    protected abstract int getLayoutId();

    /**
     * 绑定数据
     * @param holder 具体的viewHolder
     * @param data   当前Item的数据
     */
    protected abstract void bindData(BaseViewHolder holder, int position, T data);

    /**
     * 刷新数据（第一次加载数据）
     * @param datas
     */
    public void onRefresh(List<T> datas) {
        initData();
        this.datas.clear();
        if (datas != null) {
            this.datas.addAll(datas);
        }
        notifyDataSetChanged();
    }
}
